//
//  MessageViewController.m
//  SP2P
//
//  Created by 吴建东 on 16/2/29.
//  Copyright © 2016年 EIMS. All rights reserved.
//  官方公告or消息列表

#import "MessageViewController.h"
#import "MessageCell.h"
#import "MessageModel.h"
#import "MessageDetailViewController.h"
#import "FilterHTML.h"

@interface MessageViewController ()<UITableViewDelegate,UITableViewDataSource,HTTPClientDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property(nonatomic ,strong) NetWorkClient *requestClient;
@property (nonatomic, assign) NSInteger currPage;
@property (nonatomic, assign) NSInteger totalNum;
@property (nonatomic, assign) NSInteger requestType;
@property (nonatomic, assign) BOOL isLoading;
@property (nonatomic, assign) NSInteger unReadSize;
@end

@implementation MessageViewController
#pragma mark - Life Cycle
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    if (_requestClient != nil) {
        [_requestClient cancel];
    }
    [self reloadRightBarItem];
    [_tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if(iOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    [self initNavBarTitle:@"官方公告" andLeftItemName:@"返回" andRightItemName:@""];
    [self initData];
   
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    _tableView.mj_header = [MJChiBaoZiHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRereshing)];
    // 自动刷新(一进入程序就下拉刷新)
   [_tableView.mj_header beginRefreshing];
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    _tableView.mj_footer = [MJRefreshBackNormalFooter  footerWithRefreshingTarget:self refreshingAction:@selector(footerRereshing)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (void)rightBarButtonClick {
    [self setAllReadRequest];
}

#pragma mark - Action
- (void)reloadRightBarItem {
    if (_unReadSize > 0) {
        UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"已读" style:UIBarButtonItemStyleDone target:self action:@selector(rightBarButtonClick)];
        [rightButtonItem setTintColor:[UIColor whiteColor]];
        [rightButtonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,[UIFont systemFontOfSize:16.0f],NSFontAttributeName, nil] forState:UIControlStateNormal];
        self.navigationItem.rightBarButtonItem = rightButtonItem;
    }else {
        self.navigationItem.rightBarButtonItem = nil;
    }
}

#pragma mark - TableView
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_dataArray.count <= 0) {
        return;
    }
    MessageModel *model = _dataArray[indexPath.row];
    if ([model.read_status isEqualToString:@"未读"]) {
        _unReadSize --;
    }
    MessageDetailViewController *detail = [[MessageDetailViewController alloc] init];
    detail.messageModel = model;
    [self.navigationController pushViewController:detail animated:YES];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_dataArray.count > 0) {
        static NSString *CellIdentifier = @"MessageCell";
        MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (!cell) {
            cell =[[NSBundle mainBundle] loadNibNamed:@"MessageCell" owner:self options:nil][0];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [cell fillCellWithObject:_dataArray[indexPath.row]];
        
        cell.frame=CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, KAdaptNum(70));
        
        return cell;
    }else {
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"emptyCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = KbackgroundColor;
        
        UILabel *emptyLabel = [UILabel labelWithFrame:CGRectMake(0, 100, MSWIDTH, 100) text:@"" textColor:KGrayColor textFont:16.0 fitWidth:NO superview:cell];
        emptyLabel.textAlignment = NSTextAlignmentCenter;
       
        if (_isLoading) {
            emptyLabel.text = @"正在加载";
        }else {
            emptyLabel.text = @"暂无记录";
        }
        
        cell.frame=CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, _tableView.frame.size.height);
        
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self tableView:tableView cellForRowAtIndexPath:indexPath].frame.size.height;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count>0?_dataArray.count:1;
}
//  编辑删除
//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
//    [_dataArray removeObjectAtIndex:indexPath.row];
//    [_tableView reloadData];
//
//}
#pragma mark - Data
- (void)initData {
    _dataArray = [NSMutableArray array];
   
}
/**
 加载数据
 */
- (void)requestData {
    if (AppDelegateInstance.userInfo == nil) {
        [self hiddenRefreshView];
        [ReLogin outTheTimeRelogin:self];
        return;
    }
    if (_isLoading) {
        [SVProgressHUD showImage:nil status:@"正在请求,请稍后再试"];
        return;
    }
    _requestType = 1;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"518" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
   // [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"id"];
    [parameters setObject:[NSString stringWithFormat:@"%ld",(long)_currPage] forKey:@"currPage"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

- (void)setAllReadRequest {
    if (AppDelegateInstance.userInfo == nil) {
        [ReLogin outTheTimeRelogin:self];
        return;
    }
    if (_isLoading) {
        [SVProgressHUD showImage:nil status:@"正在请求,请稍后再试"];
        return;
    }
    _requestType = 2;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"223" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"userId"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

#pragma - HTTPClientDelegate 网络数据回调代理
-(void) startRequest {
    _isLoading = YES;
}

// 返回成功
-(void) httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
    [self hiddenRefreshView];
    _isLoading = NO;
    NSDictionary *dics = obj;
    DLOG(@"=交易记录返回成功=======%@",dics);
    
    if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-1"]) {
        if (_requestType == 1) {
            // 清空全部数据
            if (_currPage == 1) {
                [_dataArray removeAllObjects];
            }
            _totalNum = [[obj objectForKey:@"totalNum"] integerValue];
            NSArray *collections = [obj objectForKey:@"list"];
            for (NSDictionary *item in collections) {
                MessageModel *model = [MessageModel objectWithKeyValues:item];
                model.messageId = [NSString stringWithFormat:@"%@",[item objectForKey:@"id"]];
                model.originContent = model.content;

                model.content = [FilterHTML filterHTML:model.content];
                model.content = [model.content stringByReplacingOccurrencesOfString:@"\t" withString:@""];
                model.content = [model.content stringByReplacingOccurrencesOfString:@"\n" withString:@""];
                model.selectall = @"0";
                
                NSDate *date = [NSDate dateWithTimeIntervalSince1970:[[[item objectForKey:@"time"] objectForKey:@"time"] doubleValue]/1000];
                NSDateFormatter *dataFormat = [[NSDateFormatter alloc] init];
                [dataFormat setDateFormat:@"yyyy-MM-dd"];
                model.timeStr = [self prettyDateWithReference:date];
                model.detailTimes = [dataFormat stringFromDate:date];
                
                [_dataArray addObject:model];
            }
            
            [_tableView reloadData];
        }else if (_requestType == 2) {
            [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"%@", [obj objectForKey:@"msg"]]];
            [self requestData];
        }
        
    }else if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-2"]) {
        [ReLogin outTheTimeRelogin:self];
    }else {
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", [obj objectForKey:@"msg"]]];
    }
}

// 返回失败
-(void) httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error {
    _isLoading = NO;
    [self hiddenRefreshView];
    // 服务器返回数据异常
    //    [SVProgressHUD showErrorWithStatus:@"网络异常"];
}

// 无可用的网络
-(void) networkError {
    _isLoading = NO;
    [self hiddenRefreshView];
    [SVProgressHUD showErrorWithStatus:@"无可用网络"];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing {
    _currPage = 1;
    [self requestData];
}

- (void)footerRereshing {
    if (_totalNum > _dataArray.count) {
        _currPage ++;
        [self requestData];
    }else {
        [_tableView.mj_footer endRefreshing];
    }
}

// 隐藏刷新视图
- (void)hiddenRefreshView {
    if (!_tableView.mj_header.hidden) {
        [_tableView.mj_header endRefreshing];
    }
    if (!_tableView.mj_footer.hidden) {
        [_tableView.mj_footer endRefreshing];
    }
}


- (NSString *)prettyDateWithReference:(NSDate *)reference {
    NSString *suffix = @"ago";
    
    float different = [reference timeIntervalSinceNow];
    if (different < 0) {
        different = -different;
        suffix = @"以前";
    }
    
    // days = different / (24 * 60 * 60), take the floor value
    float dayDifferent = floor(different / 86400);
    
    int days   = (int)dayDifferent;
    int weeks  = (int)ceil(dayDifferent / 7);
    int months = (int)ceil(dayDifferent / 30);
    int years  = (int)ceil(dayDifferent / 365);
    
    // It belongs to today
    if (dayDifferent <= 0) {
        // lower than 60 seconds
        if (different < 60) {
            return @"刚刚";
        }
        
        // lower than 120 seconds => one minute and lower than 60 seconds
        if (different < 120) {
            return [NSString stringWithFormat:@"1分钟 %@", suffix];
        }
        
        // lower than 60 minutes
        if (different < 660 * 60) {
            return [NSString stringWithFormat:@"%d分钟 %@", (int)floor(different / 60), suffix];
        }
        
        // lower than 60 * 2 minutes => one hour and lower than 60 minutes
        if (different < 7200) {
            return [NSString stringWithFormat:@"1小时%@", suffix];
        }
        
        // lower than one day
        if (different < 86400) {
            return [NSString stringWithFormat:@"%d小时%@", (int)floor(different / 3600), suffix];
        }
    }
    // lower than one week
    else if (days < 7) {
        return [NSString stringWithFormat:@"%d天%@%@", days, days == 1 ? @"" : @"", suffix];
    }
    // lager than one week but lower than a month
    else if (weeks < 4) {
        return [NSString stringWithFormat:@"%d天%@%@", weeks, weeks == 1 ? @"" : @"", suffix];
    }
    // lager than a month and lower than a year
    else if (months < 12) {
        return [NSString stringWithFormat:@"%d月%@%@", months, months == 1 ? @"" : @"", suffix];
    }
    // lager than a year
    else {  
        return [NSString stringWithFormat:@"%d年%@%@", years, years == 1 ? @"" : @"", suffix];
    }  
    
    return self.description;  
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
